package com.malty.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malty.mall.dao.ums.UmsResourceTypeMapper;
import com.malty.mall.domain.dto.req.UmsResourceTypeParam;
import com.malty.mall.domain.entity.ums.UmsResourceType;
import com.malty.mall.service.ums.IUmsResourceTypeService;
import com.malty.mall.util.PreconditionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author malty
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UmsResourceTypeServiceImpl extends ServiceImpl<UmsResourceTypeMapper, UmsResourceType> implements IUmsResourceTypeService {
    @Override
    public Boolean create(UmsResourceTypeParam umsResourceTypeParam) {
        UmsResourceType umsResourceType = new UmsResourceType(umsResourceTypeParam);
        List<UmsResourceType> types = this.list(Wrappers.<UmsResourceType>lambdaQuery().orderByDesc(UmsResourceType::getSort).last("limit 1"));
        int sort = 1;
        if (!ObjectUtils.isEmpty(types)) {
            sort = types.get(0).getSort() + 1;
        }
        umsResourceType.setSort(sort);
        boolean save = this.save(umsResourceType);
        PreconditionUtils.check(!save, "创建失败");
        return true;
    }

    @Override
    public List<UmsResourceTypeParam> listAll() {
        List<UmsResourceType> resourceTypes = this.list(Wrappers.<UmsResourceType>lambdaQuery().orderByAsc(UmsResourceType::getSort));
        return UmsResourceType.getParamBatch(resourceTypes);
    }
}
